package cn.sheep.sense;

import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * author: sheep.Old
 * qq: 64341393
 * Created 2018/5/31
 */
public class ConsumerClient {

    ZooKeeper zk = null;

    // 装在线的节点列表
    static ArrayList<String> onlineServers = new ArrayList<String>();

    public static void main(String[] args) {


        try {
            ConsumerClient client = new ConsumerClient();
            // 1. 连接zk
            client.connectZookeeper();

            // 3. 随即调用某个server
            client.sendRequest();


        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 模拟发送请求
     */
    private void sendRequest() throws InterruptedException {

        while (true) {
            Thread.sleep(1000);
            //判断list里面有没有节点信息
            if (onlineServers.size() > 0) {
                Random random = new Random();
                int love = random.nextInt(onlineServers.size());

                System.out.println("本次服务的是 = " + onlineServers.get(love));
            } else {
                System.out.println("无可用服务, 请添加....");
            }
        }

    }

    private void connectZookeeper() throws IOException {
        zk = new ZooKeeper(Constant.ZKSERVER, Constant.TIMEOUT, new Watcher() {
            public void process(WatchedEvent watchedEvent) {
                // 去zk查询在线的节点
                try {
                    //查询在线的节点信息方法
                    getOnlineServers(zk);
                    System.out.println("查询了一次在线的服务器列表....");
                } catch (KeeperException e) {
                    e.printStackTrace();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * 查询/servers节点下的所有子节点信息
     *
     * @param zk
     */
    private static void getOnlineServers(ZooKeeper zk) throws KeeperException, InterruptedException {

        ArrayList<String> currentOnlineServers = new ArrayList<String>();
        //获取节点，并监听
        List<String> children = zk.getChildren(Constant.PZNODE, true);
        for (String child : children) {
            //获取节点下的数据，不需要监听，需求是获取server端上下感知。
            byte[] data = zk.getData(Constant.PZNODE + "/" + child, false, null);
            String hostNameAndPort = new String(data);
            //把节点数据保存到当前list
            currentOnlineServers.add(hostNameAndPort);
        }
        //每次节点上下线都要查一次，会造成累加和重复，需要更新旧的list集合。
        onlineServers = currentOnlineServers;
        System.out.println("当前可用的服务器列表 = " + currentOnlineServers);
    }

}
